package cn.dankal.flyaudio.activity.detail

import android.graphics.Color
import android.view.MotionEvent
import android.view.View
import api.ActivityServiceFactory
import api.UserServiceFactory
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.base.activity.BaseStateActivity
import cn.dankal.basiclib.pojo.UserInfoBean
import cn.dankal.basiclib.protocol.LoginProtocol
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.protocol.PersonalProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.rx.AbstractStateSubscriber
import cn.dankal.basiclib.util.StringUtil
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.util.image.PicUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.basiclib.widget.statubar.QMUIStatusBarHelper
import cn.dankal.business.CommonUtil.getActivityState
import cn.dankal.business.pojo.ActivityBean
import cn.dankal.business.Constants
import cn.dankal.business.pojo.ActivityReserveBean
import cn.dankal.business.pojo.ReasonBean
import cn.dankal.flyaudio.R
import cn.dankal.flyaudio.personal.notificaiton.DataFactory
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_detatil.*
import kotlinx.android.synthetic.main.layout_tag_all.*

/**
 * 活动详情
 */
@Route(path = MainProtocol.ACTIVITY_DETAIL)
class ActivityDetailActivity : BaseStateActivity() {
    override fun contentView(): Any {
        return ll_content
    }

    @Autowired(name = Constants.UUID)
    @JvmField
    var uuid: String? = null

    @Autowired(name = Constants.INTO_TYPE)
    @JvmField
    var intoType: String? = null

    @Autowired(name = "UUID_TOW")
    @JvmField
    var uuid_tow: String? = null


    lateinit var activityBean: ActivityBean

    lateinit var activityReserveBean: ActivityReserveBean

    lateinit var commonDialog: CommonDialog;

    override fun initComponents() {
        ARouter.getInstance().inject(this)
//        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarLightMode(this@ActivityDetailActivity)

//        setTranslucent(this, findViewById(R.id.ll_root))
        val uuids = arrayOfNulls<String>(1)
        uuids[0] = uuid_tow
        UserServiceFactory.update_remind(DataFactory.getMapData(uuids, 1, 0))
                .subscribe(object : AbstractDialogSubscriber<ReasonBean>(this) {
                    override fun onNext(reasonBean: ReasonBean) {
                    }
                })

        if (intoType == null) {
            bt_entry.setOnClickListener {
                try {
                    if (activityBean.applyStatus != Constants.ActivityStatus.OnProgress.statusCode) {
                        ToastUtils.showShort(bt_entry.text.toString())
                        return@setOnClickListener
                    }
                } catch (e: Exception) {
                    return@setOnClickListener
                }
                if (!DankalApplication.isLogin()) {
                    ARouter.getInstance().build(LoginProtocol.LOGIN).navigation()
                    return@setOnClickListener
                }
                commit()
            }
            activityDetail(uuid)

        } else {
            activityReserveDetail(uuid)
        }
        iv_onback.setOnClickListener {
            finish()
        }
//
//        sc_view.setOnTouchListener(object : View.OnTouchListener {
//            override fun onTouch(bg_card_details_1: View?, event: MotionEvent?): Boolean {
//                sv_view.requestDisallowInterceptTouchEvent(true)
//                return false
//            }
//        })
    }

    private fun activityDetail(uuid: String?) {
        ActivityServiceFactory.activity_details(uuid)
                .subscribe(object : AbstractStateSubscriber<ActivityBean>(this) {
                    override fun onNext(bean: ActivityBean) {
                        super.onNext(bean)
                        activityBean = bean
                        setState()
                    }
                })
    }

    private fun activityReserveDetail(uuid: String?) {
        ActivityServiceFactory.activity_reserve_info(uuid)
                .subscribe(object : AbstractStateSubscriber<ActivityReserveBean>(this) {
                    override fun onNext(bean: ActivityReserveBean) {
                        super.onNext(bean)
                        activityReserveBean = bean
                        setState()
                    }
                })
    }

    private fun commit() {

        // 判断不能为空
        if (activityBean == null || activityBean.uuid.isEmpty()) {
            ToastUtils.showShort("活动信息未完整")
            return
        }

        UserServiceFactory.getUserInfo().subscribe(object : AbstractDialogSubscriber<UserInfoBean>(this) {
            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: UserInfoBean) {
                if (t.isTourist()) {
                    checkVertifyState()
                } else {
                    ActivityServiceFactory.is_apply_activity(uuid)
                            .subscribe(object : AbstractDialogSubscriber<String>(this@ActivityDetailActivity) {
                                override fun onSubscribe(d: Disposable) {

                                }

                                override fun onNext(t: String) {
                                    ARouter.getInstance().build(MainProtocol.ENTRYCOMMIT)
                                            .withString(Constants.UUID, uuid)
                                            .withSerializable(ActivityBean::class.java.simpleName, activityBean)
                                            .navigation()
                                }

                                override fun onComplete() {

                                }
                            })
                }
            }
        })
    }

    private fun checkVertifyState() {
        val builder = CommonDialog.Builder(this)
        builder.setTitle("对不起，游客朋友，活动只对认证车主开放")

        builder.setNegativeButton("取消",
                resources.getColor(R.color.color14)) {
            commonDialog.dismiss()

        }
        builder.setPositiveButton("前去认证",
                resources.getColor(R.color.colorPrimary)) {
            ARouter.getInstance().build(PersonalProtocol.VERIFY).navigation()
            commonDialog.dismiss()
        }
        commonDialog = builder.create()
        commonDialog.show()
    }

    /**
     * 设置活动状态
     * 未报名 未开始 已结束
     */
    private fun setState() {
        if (intoType == null) {
            activityBean?.apply {
                PicUtils.loadNormal(cover, iv_img)
                tv_title.setText(title)
//                if (!StringUtil.isValid(oneTag)) {
//                    ll_tag_1.visibility = View.GONE
//                } else {
//                    ll_tag_1.visibility = View.VISIBLE
//                    tv_tag1.setText(oneTag)
//                }
//
//                if (!StringUtil.isValid(twoTag)) {
//                    ll_tag_2.visibility = View.GONE
//                } else {
//                    ll_tag_2.visibility = View.VISIBLE
//                    tv_tag2.setText(twoTag)
//                }
//                if (!StringUtil.isValid(threeTag)) {
//                    ll_tag_3.visibility = View.GONE
//                } else {
//                    ll_tag_3.visibility = View.VISIBLE
//                    tv_tag3.setText(threeTag)
//                }

//                tv_content.setText(content)
                tv_user_join.setText("已报名人数：" + applyPeopleNumber + "/" + allPeopleNumber)
                tv_view_count.setText(lookNumber.toString())
                tv_area.setText(activitySite)
                tv_time.setText("活动时间:$activityStartTime")
                var activityState = activityStatus
                setActivityStateColor(activityState)
                setApplyStateColor(this)
            }
        } else {
            activityReserveBean?.apply {
                PicUtils.loadNormal(cover, iv_img)
                tv_title.setText(title)
//                if (!StringUtil.isValid(oneTag)) {
//                    ll_tag_1.visibility = View.GONE
//                } else {
//                    ll_tag_1.visibility = View.VISIBLE
//                    tv_tag1.setText(oneTag)
//                }
//
//                if (!StringUtil.isValid(twoTag)) {
//                    ll_tag_2.visibility = View.GONE
//                } else {
//                    ll_tag_2.visibility = View.VISIBLE
//                    tv_tag2.setText(twoTag)
//                }
//                if (!StringUtil.isValid(threeTag)) {
//                    ll_tag_3.visibility = View.GONE
//                } else {
//                    ll_tag_3.visibility = View.VISIBLE
//                    tv_tag3.setText(threeTag)
//                }
//                tv_content.setText(content)
                tv_user_join.setText("已报名人数：" + applyPeopleNumber + "/" + allPeopleNumber)
                tv_view_count.setText(lookNumber.toString())
                tv_area.setText(activitySite)
                tv_time.setText(activityStartTime)
                var activityState = activityStatus
                setActivityStateColor(activityState)
                setApplyStateColor(this)
            }
        }
        ll_root.visibility = View.VISIBLE
        //sv_view.visibility=View.VISIBLE
    }

    /**
     * 设置活动状态
     */
    private fun setActivityStateColor(activityState: Int) {
        tv_detail_state.text = (getActivityState(activityState))
        if (activityState == 2) {
            //灰色的
            tv_detail_state.setTextColor(resources.getColor(R.color.color99))
        } else if (activityState == 1) {
            //蓝色的
            tv_detail_state.setTextColor(Color.parseColor("#4042FF"))
        }
    }

    /**
     * 设置报名状态
     */
    private fun setApplyStateColor(activity: ActivityBean) {
        // 如果是已经报名了
        if (activity.isApply == Constants.ApplyStatus.isApply) {
            ll_join.visibility = View.VISIBLE
            bt_entry.isEnabled = false
            bt_entry.text = "已报名"
            bt_entry.setBackgroundResource(R.drawable.base_bottom_btn_radius24_5_enable)
            ll_join_msg.visibility = View.GONE
            return
        }
        if (activity.applyStatus != 1) {
            bt_entry.isEnabled = false
            bt_entry.setBackgroundResource(R.drawable.base_bottom_btn_radius24_5_enable)
            if (activity.applyStatus == 0) {
                bt_entry.setText("活动报名还未开始")
            } else if (activity.applyStatus == 2) {
                bt_entry.setText("活动报名已结束")
            }
        }
    }

    /**
     * 显示报名人信息
     */
    private fun setApplyStateColor(activity: ActivityReserveBean) {
        ll_join.visibility = View.GONE
        ll_join_msg.visibility = View.VISIBLE
        tv_user_name.text = activity.name
        tv_user_mobile.text = activity.phone
        tv_user_join_myself.text = "人数：" + activity.carryNumber
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_detatil
    }


}
